let checkedIds = [] //存放选中的id
// 出库表 bootstrap设置
$("#outbound").bootstrapTable({
    url: "/outbound/list",
    method: "get",
    pagination: true,   //是否显示分页（*）
    pageSize: 10,       //每页的记录行数（*）
    pageList: [10, 20, 50, 100, 'All'], //可供选择的每页的行数（*）
    sidePagination: "client",    //分页方式：client客户端分页，server服务端分页（*）
    pageNumber: 1,
    classes: "table table-bordered table-striped table-condensed table-hover",                  //初始化加载第一页，默认第一页
    columns: [{
        checkbox: true,// 显示复选框
        formatter: function (i, row) {
            //判断当前id是否在存放选中id的数组中
            if ($.inArray(row.id, checkedIds) != -1) {
                return {
                    checked: true //如果存在，设置选中
                }
            }
        }
    }, {
        title: "出库id",
        field: "id",
        visible: false
    }, {
        title: "出库编号",
        field: "no",
    }, {
        title: "商品名称",
        field: "goodsName",
    }, {
        title: "出库数量(盒)",
        field: "boxNum",
    }, {
        title: "店铺名称",
        field: "shopName",
    }, {
        title: "备注",
        field: "note",
    }, {
        title: "出库数量",
        field: "num",
    }, {
        title: "出库时间",
        field: "createTime",
    }, {
        title: "核销状态",
        field: "isVerified",
        formatter: function (value) {
            if (value == 0) {
                return "未核销";
            } else if (value == 1) {
                return "已核销";
            }
        }
    }, {
        field: 'operate',
        title: '操作',
        align: 'center',
        valign: 'middle',
        width: 200,
        events: {
            'click #update': function (e, value, row, index) {
                $('#update-id').val(row.id);
                $('#update-no').val(row.no);
                $('#update-goodsId').val(row.goodsId);
                $('#update-goodsName').val(row.goodsName);
                $('#update-num').val(row.num);
                $('#update-shopId').val(row.shopId);
                $('#update-shopName').val(row.shopName);
                $('#update-note').val(row.note);
            },
            'click #delete': function (e, value, row, index) {
                $('#delete-id').val(row.id);
                $('#delete-no').val(row.no);
                $('#delete-goodsId').val(row.goodsId);
                $('#delete-goodsName').val(row.goodsName);
                $('#delete-num').val(row.num);
                $('#delete-shopId').val(row.shopId);
                $('#delete-shopName').val(row.shopName);
                $('#delete-note').val(row.note);
            }
        },
        formatter: function (value, row, index) {
            let result = "";
            result += '<button id="update" class="btn btn-info" data-toggle="modal" data-target="#updateModal">编辑</button>';
            result += '<button id="delete" class="btn btn-danger" data-toggle="modal" data-target="#deleteModal" style="margin-left:10px;width: 50px;height=25px;font-size: 15px">删除</button>';
            return result;
        }
    }]
});

$('#outbound').on('uncheck.bs.table check.bs.table check-all.bs.table uncheck-all.bs.table', function (e, rows, pageData) {
    let datas = $.isArray(rows) ? rows : [rows]; // 点击时获取选中的行或取消选中的行
    //这里有个特殊情况，当有全选功能时，如果全选然后取消得到的rows值为空数组，所以此时取值取pageData
    //通过e.type的值判断是否点击的是全选按钮
    filterData(e.type, datas)
    // e.type == 'uncheck-all' ? filterData(e.type, allData) : filterData(e.type, datas)
});

// 按要求对数据进行过滤，将选中的数据保存
function filterData(type, datas) {
    if (type == 'uncheck-all') {  //当全选取消选中项的时候，获取到当前页所有数据，
        $.each(datas, function (i, v) {
            if (v['0'] == true) {//如果为true说明是选中
                checkedIds.indexOf(v.id) == -1 ? checkedIds.push(v.id) : -1;
            } else {//说明是未选中
                checkedIds.splice(checkedIds.indexOf(v.id), 1); //删除取消选中行
            }
        });
        return
    }
    if (type.indexOf('uncheck') == -1) {
        $.each(datas, function (i, v) { // 添加时，判断一行或多行的 id 是否已经在数组里 不存则添加　
            checkedIds.indexOf(v.id) == -1 ? checkedIds.push(v.id) : -1;
        });
    } else {
        $.each(datas, function (i, v) {
            checkedIds.splice(checkedIds.indexOf(v.id), 1);//删除取消选中行
        });
    }
}

$("#search-startAndEndTime").daterangepicker({
    locale: {
        "format": 'YYYY-MM-DD HH:mm:ss',
        "separator": " - ",
        "applyLabel": "确定",
        "cancelLabel": "取消",
        "resetLabel": "重置",
        "fromLabel": "起始时间",
        "toLabel": "结束时间'",
        "customRangeLabel": "自定义",
        "weekLabel": "W",
        "daysOfWeek": ["日", "一", "二", "三", "四", "五", "六"],
        "monthNames": ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
        "firstDay": 1
    },
    ranges: {
        '今日': [moment(), moment()],
        '昨日': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
        '最近7日': [moment().subtract(6, 'days'), moment()],
        '最近30日': [moment().subtract(29, 'days'), moment()],
        '本月': [moment().startOf('month'), moment().endOf('month')],
        '上月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
        '今年': [moment().startOf('year'), moment().endOf('year')],
    },
    "alwaysShowCalendars": true,
    "startDate": moment().subtract(1, 'years'),  //1年前
    // "startDate": new Date(),
    "endDate": new Date(),
    "opens": "right",
}, function (start, end, label) {
});


function searchOutboundOnClick() {
    let startAndEndTime = $("#search-startAndEndTime").val().replace(/\s-\s/ig, '?').split('?');
    $.get({
        url: "/outbound/list",
        data: {
            no: $("#search-no").val(),
            goodsName: $("#search-goodsName").val(),
            shopName: $("#search-shopName").val(),
            startDateTime: startAndEndTime[0],
            endDateTime: startAndEndTime[1],
            isVerified: $("#search-verifiedType").val()
        },
        dataType: "json",
        success: function (data) {
            $("#outbound").bootstrapTable('load', data);
        }
    });
}

//按下Enter查询
$(document).keyup(function (event) {
    if (event.keyCode == 13){
        searchOutboundOnClick();
    }

});

$("#reset").click(function () {
    $("#search-goodsName").val("");
    $("#search-shopName").val("");
    $("#search-startAndEndTime").val("");
    $("#search-no").val("");
    $("#search-verifiedType").val("")
})

//新增时输入盒装数量，修改散装数量
function boxNumInput(tObject) {
    let tr = $(tObject).parent();
    let boxNum = $(tObject).children("input").val();
    let perBox = tr.children('[name= "perBox"]').eq(0).text();
    tr.children('[name= "num"]').eq(0).html(boxNum * perBox);
}


//新增时输入盒装数量，修改散装数量
function numInput(tObject) {
    let tr = $(tObject).parent();
    let num = $(tObject).children("input").val();
    let perBox = tr.children('[name= "perBox"]').eq(0).text();
    tr.children('[name= "boxNum"]').eq(0).html(num / perBox);
}

//新增出库 点击事件
$("#addOutbound").click(function () {
    let params = getAddOutboundList();
    $.post({
        url: "/outbound/addList",
        async: false,//同步，默认是true，异步
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(params),
        success: function (data) {
            let result = data;
            layui.use('layer', function () {
                let layer = layui.layer;
                if (result.success) {
                    layer.msg("操作成功，成功行数:   " + result.data, {icon: 1});
                } else {
                    layer.msg(result.msg, {icon: 2});
                }
            });
        }
    });
    searchOutboundOnClick();
    $("#addModal").modal('hide');
});
//批量核销
$("#batchVerified").click(function () {
    $.post({
        url: "/outbound/batchVerified",
        async: false,//同步，默认是true，异步
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(checkedIds),
        success: function (data) {
            let result = data;
            layui.use('layer', function () {
                let layer = layui.layer;
                if (result.success) {
                    layer.msg("操作成功，成功行数:   " + result.data, {icon: 1});
                } else {
                    layer.msg(result.msg, {icon: 2});
                }
            });
        }
    });
    searchOutboundOnClick();
});
//批量删除
$("#batchDelete").click(function () {
    $.post({
        url: "/outbound/batchDelete",
        async: false,//同步，默认是true，异步
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify(checkedIds),
        success: function (data) {
            let result = data;
            layui.use('layer', function () {
                let layer = layui.layer;
                if (result.success) {
                    layer.msg("操作成功，成功行数:   " + result.data, {icon: 1});
                } else {
                    layer.msg(result.msg, {icon: 2});
                }
            });
        }
    });
    searchOutboundOnClick();
});

//修改出库 点击事件
$("#updateOutbound").click(function () {
    $.post({
        url: "/outbound/update",
        async: false,//同步，默认是true，异步
        data: {
            id: $("#update-id").val(),
            no: $("#update-no").val(),
            goodsId: $("#update-goodsId").val(),
            num: $("#update-num").val(),
            shopId: $("#update-shopId").val(),
            note: $("#update-note").val(),
        },
        success: function (data) {
            let result = data;
            layui.use('layer', function () {
                let layer = layui.layer;
                if (result.success) {
                    layer.msg("操作成功，成功行数:   " + result.data, {icon: 1});
                } else {
                    layer.msg(result.msg, {icon: 2});
                }
            });
        }
    });
    searchOutboundOnClick();
    $("#updateModal").modal('hide');
});

//删除出库 点击事件
$("#deleteOutbound").click(function () {
    $.post({
        url: "/outbound/delete",
        async: false,//同步，默认是true，异步
        data: {
            id: $("#delete-id").val(),
        },
        success: function (data) {
            let result = data;
            layui.use('layer', function () {
                let layer = layui.layer;
                if (result.success) {
                    layer.msg("操作成功，成功行数:   " + result.data, {icon: 1});
                } else {
                    layer.msg(result.msg, {icon: 2});
                }
            });
        }
    });
    searchShopGoodsOnClick();
    $("#deleteModal").modal('hide');
});


//输入时弹出符合条件的店铺名称
$("#add-all-shopName").attr("oninput", "getAddShopData(this)")

//修改时 点击店铺信息输入框，模糊查询商品列表并展示
$("#update-shopName").on("input", getUpdateShopData);

//获得整个商品列表的数据，包装为参数 数组格式
function getAddOutboundList() {
    let table = $("#addGoodsTable");
    let tbody = table.children();
    let trs = tbody.children();
    let outboundList = [];
    for (let i = 1; i < trs.length; i++) {
        let tr = trs.eq(i);
        let outbound = {}
        outbound.goodsId = tr.children('[name= "goodsId"]').eq(0).text();
        outbound.goodsName = tr.children('[name= "goodsName"]').eq(0).text();
        outbound.num = tr.children('[name= "num"]').eq(0).text();
        outbound.shopId = tr.children('[name= "shopId"]').eq(0).text();
        outbound.shopName = tr.children('[name= "shopName"]').eq(0).text();
        outbound.note = tr.children('[name= "note"]').eq(0).text();
        outboundList.push(outbound);
    }
    return outboundList;
}

//商品信息表格，每个位置点击时 当前行出现输入框
function tdClick(tdObject) {
    let td = $(tdObject);
    td.attr("onclick", "");
    //1,取出当前td中的文本内容保存起来
    let text = td.text();
    //2,清空td里面的内容
    td.html(""); //也可以用td.empty();
    //3，建立一个文本框，也就是input的元素节点
    let input = $("<input>");
    //4，设置文本框的值是保存起来的文本内容
    input.width(td.width());
    input.attr("value", text);
    //输入框 移除焦点事件
    input.bind("blur", function () {
        let inputNode = $(this);
        let inputText = inputNode.val();
        let tdNode = inputNode.parent();
        tdNode.html(inputText);
        tdNode.click(tdClick);
        td.attr("onclick", "tdClick(this)");
    });
    //按下 Enter 的处理
    input.keyup(function (event) {
        let myEvent = event || window.event;
        let keyCode = myEvent.keyCode;
        if (keyCode == 13) {
            let inputNode = $(this);
            let inputText = inputNode.val();
            let tdNode = inputNode.parent();
            tdNode.html(inputText);
            tdNode.click(tdClick);
        }
    });
    //5，将 输入框和模糊搜索框 加入到td中
    let ul = $("<ul>");
    switch (td.attr("name")) {
        case "goodsName":
            ul.attr("id", "add-goods-dropdown-menu");
            ul.attr("class", "dropdown-menu pre-scrollable");
            input.attr("id", "add-goodsName");
            input.attr("oninput", "getAddGoodsData(this)");
            break;
        case "shopName":
            ul.attr("id", "add-shop-dropdown-menu");
            ul.attr("class", "dropdown-menu pre-scrollable");
            input.attr("id", "add-shopName");
            input.attr("oninput", "getAddShopData(this)");
            break;
    }
    td.append(input);
    let t = input.val();
    input.val("").focus().val(t);
    td.append(ul);
    //6,清除点击事件
    td.unbind("click");
    //在当前节点点击 不失去焦点
    td.on('mousedown', function () {
        event.preventDefault();
    });
}


//新增时 商品列表当前行数
let row = 0;

//新增一行
function addTr() {
    row++;
    let table = $("#addGoodsTable");
    let tr = $("<tr>"
        //商品id
        + "<td style='text-align: center;' name='goodsId'>" + "</td>"
        //商品名称
        + "<td style='text-align: center;' onclick='tdClick(this)' name='goodsName' autocomplete='off'>" + "</td>"
        //盒装数量
        + "<td style='text-align: center;' onclick='tdClick(this)' name='boxNum' oninput='boxNumInput(this)'>" + "</td>"
        //散装数量
        + "<td style='text-align: center;' onclick='tdClick(this)' name='num' oninput='numInput(this)'>" + "</td>"
        //规格
        + "<td disabled style='text-align: center;' onclick='tdClick(this)' name='perBox'>" + "</td>"
        //供应商id
        + "<td style='text-align: center;' name='shopId'>" + $("#add-all-shopId").val() + "</td>"
        //供应商名称
        + "<td style='text-align: center;' onclick='tdClick(this)' autocomplete='off' name='shopName'>" + $("#add-all-shopName").val() + "</td>"
        //备注
        + "<td style='text-align: center;' onclick='tdClick(this)' name='note'>" + $("#add-all-note").val() + "</td>"
        //操作
        + "<td align='center' onclick='trDelete(this)'><button type='button' class='btn btn-xs btn-link' >" + "删除" + "</button></td>"
        + "</tr>");
    table.append(tr);
}

//删除一行
function trDelete(tdObject) {
    row--;
    let td = $(tdObject);
    td.parents("tr").remove();
}

//模糊搜索 输入信息 ，返回符合条件的商品列表
function getAddGoodsData(inputObj) {
    $.get({
        url: "/goods/list",
        data: {
            goodsName: $(inputObj).val()
        },
        success: function (data) {
            let htmlAdd = ''
            data.forEach(function (item) {
                htmlAdd +=
                    `<li>
                            <a id=${item.id} name=${item.goodsName} onclick="chooseAddGoods(id,name,this)" href="javascript:;">${item.goodsName}</a>
                            <a name=${item.perBox} href="javascript:;" display="none"></a>
                         </li>`
            })
            $('#add-goods-dropdown-menu').html(htmlAdd)
            $('#add-goods-dropdown-menu').show()
        }
    });
}

//点击弹出的模糊搜索列表，为当前行填充数据，并隐藏模糊搜索列表
function chooseAddGoods(id, name, tObject) {
    let perBox = $(tObject).next().attr("name")
    let tr = $("#add-goodsName").parent().parent();
    tr.children('[name="goodsId"]').eq(0).html(id);
    tr.children('[name="goodsName"]').eq(0).html(name);
    tr.children('[name="perBox"]').eq(0).html(perBox);
    $('#add-goods-dropdown-menu').hide();
}

//新增时 模糊搜索 输入信息 ，返回符合条件的店铺列表
function getAddShopData(inputObj) {
    let input = $(inputObj);
    let ul = input.next();
    $.get({
        url: "/shop/list",
        data: {
            shopName: input.val()
        },
        success: function (data) {
            ul.html("");
            data.forEach(function (item) {
                let li = `<li>
                            <a id=${item.id} name=${item.shopName} onclick="chooseAddShop(this,id,name)" href="javascript:;">${item.shopName}</a>
                         </li>`
                ul.append(li);
            });
            ul.show();
        }
    });

}

function chooseAddShop(aObj, id, name) {
    let input = $(aObj).parent().parent().prev()
    let tag = input.parent().prop('nodeName');
    if (tag == 'TD') {
        input.parent().prev().html($(aObj).attr("id"))
    } else if (tag = 'DIV') {
        input.parent().parent().prev().children("div").children("input").val($(aObj).attr("id"))
    }
    input.val($(aObj).attr("name"));
    $(aObj).parent().parent().hide();
}

//修改时 模糊搜索 输入信息 ，返回符合条件的店铺列表
function getUpdateShopData() {
    $.get({
        url: "/shop/list",
        data: {
            shopName: $("#update-shopName").val()
        },
        success: function (data) {
            let htmlAdd = ''
            data.forEach(function (item) {
                htmlAdd +=
                    `<li>
                            <a id=${item.id} name=${item.shopName} onclick="chooseUpdateShop(id,name)" href="javascript:;">${item.shopName}</a>
                         </li>`

            })
            $('#update-shop-dropdown-menu').html(htmlAdd)
            $('#update-shop-dropdown-menu').show()
        }
    });
}

//点击弹出的模糊搜索列表，为当前行填充数据，并隐藏模糊搜索列表
function chooseUpdateShop(id, name) {
    $("#update-shopId").val(id);
    $("#update-shopName").val(name);
    $('#update-shop-dropdown-menu').hide();
}

//点击其他位置时，隐藏弹出的模糊搜索列表
document.addEventListener('click', function (e) {//监听页面点击事件
    let screenDoc = document.querySelector('.dropdown-menu');//需要关闭的div
    if (screenDoc && !screenDoc.contains(e.target)) {
        screenDoc.style.display = "none";
    }
}, false);
